//
//  SettingsView.swift
//  School
//
//  Created by qh w on 2021/5/3.
//

import SwiftUI

struct SettingsView: View {
    @State var server = ""
    @State var downloadFrom = ""
    @State var postTo = ""
    @State var teacherName = ""
    @State var httpServer = ""
    @State var httpServerPort = ""
    @State var showError = false
    @State var showWarning = false
    @State var showProgress = false
    @State var showCloseButton = false
    @State var showTeacherTextField = false
    @State var isChecking = false
    @State var UIAController = UIAlertController()
    @Environment(\.presentationMode) var presentation
    @EnvironmentObject var UserData: CoreData
    @State var once = false
    @State var showInitButton = false
    var body: some View {
        DispatchQueue.main.async {
            if !once {
                server = UserDefaults(suiteName: "group.classmanager")!.string(forKey: "server") ?? ""
                downloadFrom = UserDefaults(suiteName: "group.classmanager")!.string(forKey: "downloadFrom") ?? ""
                postTo = UserDefaults(suiteName: "group.classmanager")!.string(forKey: "postTo") ?? ""
                teacherName = UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") ?? ""
                httpServer = UserDefaults(suiteName: "group.classmanager")!.string(forKey: "httpServer") ?? ""
                httpServerPort = UserDefaults(suiteName: "group.classmanager")!.string(forKey: "httpServerPort") ?? ""
                once = true
            }
        }
        return Form {
            Section(header: Text("http服务器设置")) {
                TextField("服务器地址", text: $httpServer)
                    .keyboardType(.asciiCapable)
            }
            Section(footer: Text("$fileName$代表文件名，适用于GET方法")) {
                TextField("下载路径", text: self.$downloadFrom)
                    .keyboardType(.asciiCapable)
            }
            Section(footer: Text("$fileName$代表文件名，适用于POST方法")) {
                TextField("服上传路径", text: self.$postTo)
                    .keyboardType(.asciiCapable)
            }
            Section {
                Button(action: {
                    save()
                    DispatchQueue.main.async {
                        // 进入后台
                        UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
                        // 结束应用
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
                          UIApplication.shared.perform(Selector(("terminateWithSuccess")))
                        }
                    }
                }) {
                    Text("重新载入app")
                }
            }
            if showInitButton {
                Section(footer: Text("首次使用服务器，点击此按钮进行初始化，完成后请重新打开app\n注意：初始化将导致原有数据丢失")) {
                    Button(action: {
                        UIAController = UIAlertController(title: "警告", message: "注意：初始化将导致原有数据丢失", preferredStyle: .alert)
                        UIAController.addAction(UIAlertAction(title: "取消", style: .cancel))
                        UIAController.addAction(UIAlertAction(title: "仍然继续", style: .destructive, handler: { _ in
                            RunAfterVierified {
                                let newData = CoreData(classNameStr: UserData.classNameStr)
                                _ = newData.uploadDataByHttp()
                            }
                        }))
                        showWarning = true
                    }) {
                        Text("初始化").foregroundColor(.red)
                    }
                }
            }
            if showTeacherTextField {
                Section(footer: Text("进行该项设置后必须重新启动App")) {
                    HStack {
                        Text("教师姓名:")
                        TextField("姓名", text: self.$teacherName)
                    }
                }
            }
        }
        .background(SUIAController(showAlert: $showWarning, $UIAController))
        .navigationBarTitle("设置")
        .navigationBarItems(leading: showCloseButton ? Button(action: {
            presentation.wrappedValue.dismiss()
        }) {
            Text("取消")
        }:nil, trailing: VStack {
            if showProgress {
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle())
            }
            else {
                Button(action: {
                    save()
                    showProgress = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        let testData = CoreData(classNameStr: "THIS_IS_JUST_A_TEST_FILE")
                        _ = testData.uploadDataByHttp()
                        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                            _ = testData.downloadDataByHttp(stateCode: nil)
                            DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
                                if testData.fileProviderError != nil {
                                    // MARK: Show Error
                                    UIAController = UIAlertController(title: "错误", message: "服务器信息填写有误，错误代码:" + (testData.fileProviderError?.localizedDescription ?? ""), preferredStyle: .alert)
                                    UIAController.addAction(UIAlertAction(title: "确定", style: .default))
                                    showWarning = true
                                    showProgress = false
                                    return
                                }
                                presentation.wrappedValue.dismiss()
                            }
                        }
                    }
                }) {
                    Text("完成")
                }
            }
        })
        
    }
    private func save() {
        UserDefaults(suiteName: "group.classmanager")!.set(server, forKey: "server")
        UserDefaults(suiteName: "group.classmanager")!.set(downloadFrom, forKey: "downloadFrom")
        UserDefaults(suiteName: "group.classmanager")!.set(postTo, forKey: "postTo")
        UserDefaults(suiteName: "group.classmanager")!.set(httpServer, forKey: "httpServer")
        UserDefaults(suiteName: "group.classmanager")!.set(httpServerPort, forKey: "httpServerPort")
        if showTeacherTextField {
            UserDefaults(suiteName: "group.classmanager")!.set(teacherName, forKey: "teacherName")
        }   
    }
}
